package com.vista.beans.obra;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.comun.filtro.FiltroLista;
import com.facade.obra.IGestionObra;
import com.facade.utils.UtilsFacade;
import com.modelo.entity.Obra;

@Component("LazyObraDataModel")
@Scope("session")
// tiene que ser session para que guarde los datos en la sesion, puesto que son
// necesarios.
public class LazyObraDataModel extends LazyDataModel<Obra> {

	private static final long serialVersionUID = 1L;
	private List<Obra> datasource;

	@Autowired
	private IGestionObra iGestionObra;

	public LazyObraDataModel() {
		// this.datasource = datasource;
	}

	public List<Obra> getDatasource() {
		return datasource;
	}

	@Override
	public Obra getRowData(String rowKey) {
		for (Obra obra : datasource) {
			if (obra.getId().equals(Integer.valueOf(rowKey))) {
				return obra;
			}
		}

		return null;
	}

	@Override
	public Integer getRowKey(Obra obra) {
		return obra.getId();
	}

	@Override
	public List<Obra> load(int first, int pageSize, String sortField, SortOrder sortOrder,
			Map<String, String> filters) {

		Order order = UtilsFacade.convertSortOrderToOrder(sortOrder, sortField);

		FiltroLista filtro = new FiltroLista(first, pageSize, order, filters);

		filtro.setObtenerTotal(true);
		datasource = iGestionObra.getObrasActivas(filtro);

		this.setRowCount(iGestionObra.getTotal());

		return datasource;
	}

	public void setDatasource(List<Obra> datasource) {
		this.datasource = datasource;
	}

}
